package ae.pcfc.etks.online.web.controller.user.general.employee;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.support.RequestContextUtils;

import ae.pcfc.etks.online.common.delegate.SecretQuestionDelegate;
import ae.pcfc.etks.online.common.delegate.ServiceDelegate;
import ae.pcfc.etks.online.common.delegate.UserDelegate;
import ae.pcfc.etks.online.common.vo.ClientCompanyVO;
import ae.pcfc.etks.online.common.vo.LabelVO;
import ae.pcfc.etks.online.common.vo.SecretQuestionVO;
import ae.pcfc.etks.online.common.vo.ServiceVO;
import ae.pcfc.etks.online.common.vo.UserVO;
import ae.pcfc.etks.online.web.ConstantsAdmin;
import ae.pcfc.etks.online.web.PageType;
import ae.pcfc.etks.online.web.ViewPath;
import ae.pcfc.etks.online.web.ViewUtils;
import ae.pcfc.etks.online.web.controller.BaseController;
import ae.pcfc.etks.online.web.controller.user.management.manage.UserManagementController;
import ae.pcfc.etks.online.web.model.CompanyEmployee;
import ae.pcfc.etks.online.web.model.Service;
import ae.pcfc.etks.online.web.util.SecurityUtils;

/* $Id: EmployeeController 
 * Copyright (C) 2011, Trakhees
 *  
 *  History
 *
 * Date  			Author 					Remarks
 * -------------------------------------------------------------
 * Jan 4, 2012 		Ismail 	        Created
 *
 */

/**
 * Controller that handles all {@link UserManagementController}-related
 * requests, i.e.: all requests for /user/general/employee/*
 * 
 * @author Ismail
 */

@Controller
@RequestMapping(ViewPath.COMPANY_EMPLOYEE)
public class EmployeeController extends BaseController {

	private static Logger log = LoggerFactory
			.getLogger(EmployeeController.class);

	private UserDelegate userDelegate;

	@Resource(name = "userDelegate")
	public void setUserDelegate(UserDelegate userDelegate) {
		this.userDelegate = userDelegate;
	}

	private SecretQuestionDelegate secretQuestionDelegate;

	@Resource(name = "secretQuestionDelegate")
	public void setSecretQuestionDelegate(
			SecretQuestionDelegate secretQuestionDelegate) {
		this.secretQuestionDelegate = secretQuestionDelegate;
	}

	private ServiceDelegate serviceDelegate;

	@Resource(name = "serviceDelegate")
	public void setServiceDelegate(ServiceDelegate serviceDelegate) {
		this.serviceDelegate = serviceDelegate;

	}

	public ClientCompanyVO populateClientInfo() {
		Object principal = SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal();
		String strUserName;
		if (principal instanceof UserDetails) {
			strUserName = ((UserDetails) principal).getUsername();
		} else {
			strUserName = principal.toString();
		}

		UserVO userVO = userDelegate.findUserByUserName(strUserName);

		ClientCompanyVO client = null;
		if (userVO != null) {
			client = userVO.getClient();
		}
		return client;
	}

	@ModelAttribute(ConstantsAdmin.USER_SECRETQUESTION_REQUEST_MODEL_KEY)
	public List<LabelVO> populateSecretQuestionList() {

		List<LabelVO> labelList = new ArrayList<LabelVO>();

		LabelVO labelVO;
		List<SecretQuestionVO> secretQuestionVOs = secretQuestionDelegate
				.getSecretQuestionList();

		for (SecretQuestionVO secretQuestionVO : secretQuestionVOs) {
			labelVO = getMapper().map(secretQuestionVO, LabelVO.class);
			labelList.add(labelVO);

		}
		return labelList;
	}

	/**
	 * Custom handler for displaying the form, i.e.: GET requests for
	 * user/general/employee/profile/form.htm
	 * 
	 * @see WEB-INF/jsp/user/general/employee/profile/form.htm
	 */
	@RequestMapping(value = "/profile/form.htm", method = RequestMethod.GET)
	public void edit(
			HttpServletRequest request,
			Model model,
			@ModelAttribute(ConstantsAdmin.USER_PERSON_INFO_MODEL_KEY) CompanyEmployee companyEmployee,
			Locale locale) {
		Object principal = SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal();
		String strUserName;
		if (principal instanceof UserDetails) {
			strUserName = ((UserDetails) principal).getUsername();
		} else {
			strUserName = principal.toString();
		}

		UserVO userVO = this.userDelegate.findUserByUserName(strUserName);

		if (userVO != null) {
			getMapper().map(userVO, companyEmployee);

			List<ServiceVO> serviceVOs = this.serviceDelegate
					.findServiceListByUserName(companyEmployee.getStrUserName());
			List<Long> listServiceIds = new ArrayList<Long>();
			if (serviceVOs != null) {
				for (ServiceVO serviceVO : serviceVOs) {
					listServiceIds.add(serviceVO.getStrServiceID());
				}
			}

			companyEmployee.setArrServices(listServiceIds);
			List<Service> serviceModels = new ArrayList<Service>();
			if (serviceVOs != null && serviceVOs.size() > 0) {
				Service service;
				for (ServiceVO serviceVO : serviceVOs) {
					service = new Service();
					getMapper().map(serviceVO, service);
					serviceModels.add(service);
				}
			}
			model.addAttribute(ConstantsAdmin.EMPLOYEE_SERVICE_LIST,
					serviceModels);
		}
	}

	/**
	 * Custom handler for displaying the form, i.e.:POST requests for
	 * WEB-INF/jsp/user/general/employee/profile/form.htm
	 * 
	 * @see #form(Service)
	 * @see WEB-INF/jsp/user/general/employee/profile/form.htm
	 */

	@RequestMapping(method = RequestMethod.POST, value = "/profile/form.htm")
	public String edit(
			HttpServletRequest request,
			HttpSession session,
			SessionStatus status,
			Locale locale,
			@ModelAttribute(value = ConstantsAdmin.USER_PERSON_INFO_MODEL_KEY) CompanyEmployee companyEmployee,
			BindingResult errors) {

		String[] messageArgs = new String[] { getMessageSource().getMessage(
				"success.user.info.edit", null,
				RequestContextUtils.getLocale(request)) };

		UserVO userVO = null;
		userVO = userDelegate.findUserByUserName(companyEmployee
				.getStrUserName());
		if (userVO == null) {
			return ViewUtils.DEFAULT_VIEW;
		}

		userVO.setStrPassword(SecurityUtils.hashPassword(companyEmployee
				.getStrPassword()));
		ClientCompanyVO client = populateClientInfo();
		userVO.setClient(client);

		serviceDelegate.updateEmployee(userVO, null);

		session.setAttribute(ConstantsAdmin.SUCCESS_PARAM, getMessageSource()
				.getMessage("success.employee.profile.update", null, locale));
		return ViewUtils.getRedirect(ViewPath.USER_GENERAL_HOME, PageType.SHOW);
	}

}
